<template>
  <div class="status" @click="init">
    <span
      :class="{
        's-lamp': true,
        'bg-red': !status.isOpen,
        'bg-green': status.isOpen,
      }"
    ></span>
    <span
      :class="{
        's-lamp': true,
        'bg-red': !status.hasToken,
        'bg-green': status.hasToken,
      }"
    ></span>
    <span
      :class="{
        's-lamp': true,
        'bg-red': !status.noError,
        'bg-green': status.noError,
      }"
    ></span>
    <span
      :class="{
        's-lamp': true,
        'bg-red': !status.isHeart,
        'bg-green': status.isHeart,
      }"
    ></span>
  </div>
  <!-- {{ wsToken }} -->
  <!-- {{ tcpUserType }} -->
  <!-- {{ tcpUserInfo }} -->
</template>

<script>
const { config } = require('@/../config/axios_config.js');
console.log(
  '%c [ config ]-39',
  'font-size:13px; background:pink; color:#bf2c9f;',
  config
);

import MD5 from 'md5';
import { bus } from '@/bus.js';
import WSK from './../../assets/websocket.js';
import { dateFormat } from '../../assets/dataFormat';
import storage from '@/assets/storage.js';
import { findFirstValid } from '@/units/myfun.js';

export default {
  name: 'wsk',
  components: {},
  computed: {},
  props: {
    timeHeart: {
      type: Number,
      default: 1000 * 60,
    },
  },
  data() {
    return {
      isDev: process.env.NODE_ENV == 'development',
      status: {
        isOpen: false,
        hasToken: false,
        noError: true,
        isHeart: false,
      },
      wsToken: '',
      webSocket: null, //建立的连接
      readyState: 0,
      tcpUserType: 0, // 客户端类型 0:员工 1:客户
      tcpUserInfo: null,
      wsTime: null,
      sendHeartTime: 1000 * 60,
      setTimeHeartTime: null,
    };
  },
  methods: {
    init: function() {
      if (this.webSocket != null) {
        this.webSocket.stop();
        this.webSocket = null;
      }
      let loginInfo = this.tcpUserInfo;

      if (loginInfo.userName == '') return;
      this.initWebSocket().then((res) => {
        if (res.code == 200) {
          this.webSocket.send(loginInfo);
        }
      });
    },
    initWebSocket: function() {
      let self = this;
      console.log(
        '%c [ self.$config.ws ]-101',
        'font-size:13px; background:pink; color:#bf2c9f;',
        self.$config
      );
      self.webSocket = new WSK({
        isDev: self.isDev,
        // host:devWs,
        // host: "ws://192.168.11.50:8181",
        host: self.$config.ws,
        timeHeart: self.sendHeartTime, //self.timeHeart,
        strBegin: '',
        strEnd: '<EOF>',
        strHeart: 'KEEPALIVE',
        isAutoLink: false,
        autoLinkMax: 1,
        wsObj: Object.assign({}, this.tcpUserInfo),
        beforeOpen: (ws, e) => {
          this.status.isOpen = false;
          return Promise.resolve(200);
        },
        afterOpen: (ws, e) => {
          this.status.isOpen = true;
          // console.log(this.tcpUserInfo);
          // ws.send(this.tcpUserInfo);
          this.$set(this.tcpUserInfo, 'loginType', 1);
          return Promise.resolve(202);
        },
        beforeSendHeart: (ws) => {
          this.status.isHeart = false;
        },
        afterGetHeart: (ws) => {
          this.readyState = this._.get(
            this.webSocket,
            'socket.readyState',
            null
          );
          this.status.isHeart = true;
          // console.log('isHeart');
          this.resetTimeHeart();
        },
        beforeMessage: (ws, msg, e) => {
          // console.log(msg);
        },
        afterMessage: (ws, json, e) => {
          this.msgHandle(json);
        },
        beforeError: (err) => {
          this.status.noError = false;
        },
        afterClose: (err) => {
          this.readyState = this._.get(
            this.webSocket,
            'socket.readyState',
            null
          );
          this.status.isOpen = false;
          console.log('被踢了');
        },
      });
      self.webSocket.start();
      return Promise.resolve({
        code: 200,
        msg: `${self.$options.name}初始化完成`,
      });
    },

    msgHandle: function(wsMsg) {
      let roomId = this._.get(this.$route, 'query.roomId');
      if (!this._.has(wsMsg, 'tcpCode')) return;
      // console.log(wsMsg);

      /// 1:登录 ClientLogin
      if (wsMsg.tcpCode == 1) {
      }
      if (wsMsg.tcpCode == 2) {
        if (wsMsg.isSuccess) {
          bus.$emit('ws身份认证成功', Object.assign(wsMsg, { roomId: roomId }));
        } else {
          this.webSocket.stop();
          this.webSocket = null;
          this.$toasted.show(wsMsg.errMsg);
          this.$router.push({
            path: '/login',
            query: { ...this.$route.query },
          });
        }
        clearTimeout(this.wsTime);
      }
      if (wsMsg.roomId != roomId) return;
      if (wsMsg.tcpCode == 3) {
        bus.$emit('某个用户发言', wsMsg);
      }
      if (wsMsg.tcpCode == 4) {
        bus.$emit('消息审核状态改变', wsMsg);
      }
      if (wsMsg.tcpCode == 5) {
        // bus.$emit('某用户在聊天室点赞', wsMsg);
      }
      /// 6:客户权限设置 CustomerSet
      if (wsMsg.tcpCode == 6) {
        bus.$emit('某个用户权限变更', wsMsg);
      }
      if (wsMsg.tcpCode == 7) {
        if (wsMsg.state == 1) {
          bus.$emit('某用户进出聊天室', wsMsg);
        }
      }
      if (wsMsg.tcpCode == 8) {
        bus.$emit('某房间在线人数更新', wsMsg);
      }
      if (wsMsg.tcpCode == 9) {
        bus.$emit('当前用户可能异地登录', wsMsg);
      }
    },
    resetTimeHeart: function() {},
  },

  mounted: function() {
    let ceid = this._.get(this.$route.query, 'companyEmployeeId');
    this.tcpUserType = !this._.isUndefined(ceid) ? 0 : 1; // 客户端类型 0:员工 1:客户
    let loginInfo = {
      loginType: 0, // 0:正常登录 1:掉线重连
      tcpCode: 1,
      userType: this.tcpUserType,
    };

    // prettier-ignore
    if (this.tcpUserType == 0) {// 0:员工
      this._.set(loginInfo, 'companyEmployeeId',ceid);
    } else {//1:客户
      let unionId = this._.get(this.$route.query, 'unionId')
      let user = this.$store.getters.getUser;
      
      let userName = findFirstValid(
        (v) => {
          return v != '';
        },
        user.userName,
        storage.getLS('userName'),
      );

      let userPwd = findFirstValid(
        (v) => {
          return v != '';
        },
        user.userPwd,
        storage.getLS('userPwd'),
      );

      this._.set(loginInfo, 'unionId', unionId)
      this._.set(loginInfo, 'userName',userName )
      this._.set(loginInfo, 'userPwd', userPwd)
    }

    let now = dateFormat(new Date(), 'yyyy-MM-dd')
      .split('-')
      .join('');
    this._.set(loginInfo, 'verifykey', MD5(now).toUpperCase());
    this.tcpUserInfo = loginInfo;

    this.init();
    // bus.$on('', () => { })

    bus.$on('ws身份认证成功', (wsMsg) => {
      if (wsMsg.roomId != this._.get(this.$route, 'query.roomId')) return;
      this.wsToken = this._.get(wsMsg, 'token', '');
      this.status.hasToken = true;
    });
    bus.$on('当前用户可能异地登录', () => {
      this.webSocket.stop();
      this.webSocket = null;
      this.status.hasToken = false;
    });
    bus.$on('token验证失败', () => {
      this.init();
    });
  },
  beforeDestroy() {},
  destroyed() {
    this.webSocket.stop();
    this.webSocket = null;
    bus.$off('ws身份认证成功');
    bus.$off('当前用户可能异地登录');
    bus.$off('token验证失败');
  },
};
</script>

<style lang="less">
.status {
  position: fixed;
  top: unit((100 / 16 * 9), vw);
  right: 0;
  font-size: 0;
  @media screen and(min-width:1024px) {
    top: 20px;
  }
  .s-lamp {
    display: inline-block;
    width: 4px;
    height: 4px;
    margin: 2px;
  }
  .bg-red {
    background-color: red;
  }
  .bg-green {
    background-color: green;
  }
}
</style>
